﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace NTQOnlineExam.Services.Infrastructure.Utility
{
    public static class StringUtilities
    {
        public static IList<T> ParseCommaSeparatedStringToList<T>(string text)
        {
            IList<T> result = new List<T>();
            if (string.IsNullOrEmpty(text)) return result;

            string[] arrayOfElements = text.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string element in arrayOfElements)
            {
                result.Add((T)Convert.ChangeType(element, typeof(T))); // This method not support convert to GUID so we need below way to work around
                //   result.Add(element.ToType<T>());
            }
            return result;
        }

        public static String NormalizeFileName(String value)
        {
            if (value == null) return string.Empty;
            return new Regex(string.Format("[{0}]", Regex.Escape(@"<>:""/\|?*"))).Replace(value, string.Empty).Trim();
        }

        public static DateTime? ToNullableDateTime(this string s, string dateFormat)
        {
            return s.ToNullableDateTime(CultureInfo.InvariantCulture, dateFormat);
        }

        public static DateTime? ToNullableDateTime(this string s, IFormatProvider formatProvider, string dateFormat)
        {
            DateTime? result = null;
            string value = s.Trim();
            if (!string.IsNullOrEmpty(value))
            {
                DateTime dt;
                if (DateTime.TryParseExact(value, dateFormat, formatProvider, DateTimeStyles.None, out dt)) result = dt;
            }
            return result;
        }

    }
}
